package com.android.love.web;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebViewClient;
import android.widget.EditText;

import com.android.love.R;
//import com.android.love.ui.MyWebViewActivity;
import com.android.love.util.LogUtil;

import java.net.InterfaceAddress;

public class CustomWebViewClient extends WebViewClient {
    public static final String TAG = "CustomWebViewClient";
    private Context context;
    private CustomWebViewClientLister lister;
//	private MyWebViewActivity myWebActivity;


	public CustomWebViewClient(Context context) {
		super();
		this.context = context;
	}

    public interface CustomWebViewClientLister {
        void onPageFinished(String url);

        void onPageStarted(String url);

        void onReceivedError(String url);

        void onExternalApplicationUrl(String url);

        void onMailTo(String url);

        void onUrlLoading(String url);
    }

    public void setCustomWebViewClientLister(CustomWebViewClientLister lister) {
        this.lister = lister;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        LogUtil.e(TAG, "onPageFinished");
        ((CustomWebView) view).notifyPageFinished();
        lister.onPageFinished(url);
        super.onPageFinished(view, url);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        LogUtil.e(TAG, "onPageStarted");

        ((CustomWebView) view).notifyPageStarted();
        lister.onPageStarted(url);

        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onReceivedError(WebView view, int errorCode,
                                String description, String failingUrl) {
        LogUtil.e(TAG, "onReceivedError");
        lister.onReceivedError(failingUrl);
        super.onReceivedError(view, errorCode, description, failingUrl);
    }

    @Override
    public void onReceivedSslError(WebView view, final SslErrorHandler handler,
                                   SslError error) {
        LogUtil.e(TAG, "onReceivedSslError");
        StringBuilder sb = new StringBuilder();

        sb.append(view.getResources().getString(
                R.string.Commons_SslWarningsHeader));
        sb.append("\n\n");

        if (error.hasError(SslError.SSL_UNTRUSTED)) {
            sb.append(" - ");
            sb.append(view.getResources().getString(
                    R.string.Commons_SslUntrusted));
            sb.append("\n");
        }

        if (error.hasError(SslError.SSL_IDMISMATCH)) {
            sb.append(" - ");
            sb.append(view.getResources().getString(
                    R.string.Commons_SslIDMismatch));
            sb.append("\n");
        }

        if (error.hasError(SslError.SSL_EXPIRED)) {
            sb.append(" - ");
            sb.append(view.getResources()
                    .getString(R.string.Commons_SslExpired));
            sb.append("\n");
        }

        if (error.hasError(SslError.SSL_NOTYETVALID)) {
            sb.append(" - ");
            sb.append(view.getResources().getString(
                    R.string.Commons_SslNotYetValid));
            sb.append("\n");
        }

        ApplicationUtils.showContinueCancelDialog(view.getContext(),
                android.R.drawable.ic_dialog_info, view.getResources()
                .getString(R.string.Commons_SslWarning), sb.toString(),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        handler.proceed();
                    }

                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        handler.cancel();
                    }
                }
        );
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        LogUtil.e(TAG, "url---" + url);
        if (isExternalApplicationUrl(url)) {
            LogUtil.e(TAG, "isExternalApplicationUrl");
            lister.onExternalApplicationUrl(url);
            return true;

        } else if (view.getHitTestResult() != null
                && view.getHitTestResult().getType() == HitTestResult.EMAIL_TYPE) {
            LogUtil.e(TAG, "getHitTestResult");
            lister.onMailTo(url);
            return true;

        } else {
            LogUtil.e(TAG, "resetLoadedUrl");
            ((CustomWebView) view).resetLoadedUrl();
            lister.onUrlLoading(url);
            return false;
            // }
        }
    }

    @Override
    public void onReceivedHttpAuthRequest(WebView view,
                                          final HttpAuthHandler handler, final String host, final String realm) {
        LogUtil.i(TAG, "mCurrentWebView---onJsPrompt");
        String username = null;
        String password = null;

        boolean reuseHttpAuthUsernamePassword = handler
                .useHttpAuthUsernamePassword();

        if (reuseHttpAuthUsernamePassword && view != null) {
            String[] credentials = view
                    .getHttpAuthUsernamePassword(host, realm);
            if (credentials != null && credentials.length == 2) {
                username = credentials[0];
                password = credentials[1];
            }
        }

        if (username != null && password != null) {
            handler.proceed(username, password);
        } else {
            LayoutInflater factory = LayoutInflater.from(context);
            final View v = factory.inflate(R.layout.http_authentication_dialog,
                    null);

            if (username != null) {
                ((EditText) v.findViewById(R.id.username_edit))
                        .setText(username);
            }
            if (password != null) {
                ((EditText) v.findViewById(R.id.password_edit))
                        .setText(password);
            }

            AlertDialog dialog = new AlertDialog.Builder(context)
                    .setTitle(
                            String.format(
                                    context
                                            .getString(R.string.HttpAuthenticationDialog_DialogTitle),
                                    host, realm))
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setView(v)
                    .setPositiveButton(R.string.Commons_Proceed,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    ;
                                    String nm = ((EditText) v
                                            .findViewById(R.id.username_edit))
                                            .getText().toString();
                                    String pw = ((EditText) v
                                            .findViewById(R.id.password_edit))
                                            .getText().toString();
//									myWebActivity.setHttpAuthUsernamePassword(
//											host, realm, nm, pw);
                                    handler.proceed(nm, pw);
                                }
                            })
                    .setNegativeButton(R.string.Commons_Cancel,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    handler.cancel();
                                }
                            })
                    .setOnCancelListener(
                            new DialogInterface.OnCancelListener() {
                                public void onCancel(DialogInterface dialog) {
                                    handler.cancel();
                                }
                            }).create();

            dialog.getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            dialog.show();

            v.findViewById(R.id.username_edit).requestFocus();
        }
    }

    private boolean isExternalApplicationUrl(String url) {
        return url.startsWith("vnd.") || url.startsWith("rtsp://")
                || url.startsWith("itms://") || url.startsWith("itpc://")
                || url.startsWith("itaobao://")
                || url.startsWith("culiujiukuaijiu://");
    }

}
